1921D - Very Different Array - CodeForces Solution


greedy

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define ios ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long
#define ull unsigned long long
#define inf INT_MAX
#define llinf LLONG_MAX
#define mt make_tuple
#define mp make_pair
#define parll pair<ll,ll>
#define parii pair<int,int>
#define frs first
#define sec second
#define neparno(x) (x&1)
#define parno(x) (!neparno(x))
#define lowbit(x) (x&-x)
#define nzd __gcd
#define nzs(e1,e2) ((e1*e2)/nzd(e1,e2))
#define yes cout << "Yes\n"
#define no cout << "No\n"
#define yesno(x) cout << ((x)?"Yes\n":"No\n")
#define condcout(x,y,z) cout << ((x)?y:z) << "\n"
#define all(V) V.begin(),V.end()
#define fill(V,v) fill(all(V),v)
#define l_b(BRL,brl) lower_bound( BRL.begin(), BRL.end(), brl )-BRL.begin()-1
#define u_b(BRU,bru) upper_bound( BRU.begin(), BRU.end(), bru )-BRU.begin()
#define mod 1000000007
#define mxn 200002

ll q,n,m,A[mxn],B[mxn];

int main()
{
    ios;

    cin >> q;
    while ( q-- )
    {
        cin >> n >> m;
        for ( ll i = 1; i <= n; i++ )
        {
            cin >> A[i];
        }
        for ( ll i = 1; i <= m; i++ )
        {
            cin >> B[i];
        }
        sort(A+1,A+n+1);
        sort(B+1,B+m+1);

        ll x = 0;
        for ( ll i = 1; i <= n; i++ )
        {
            x += abs(B[m-i+1]-A[i]);
        }

        ll rez = x;
        for ( ll i = 1; i <= n; i++ )
        {
            rez = max( rez, x=x-abs(A[n-i+1]-B[m-(n-i+1)+1])+abs(A[n-i+1]-B[i]) );
        }
        cout << rez << "\n";
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

148A - Insomnia cure
1650A - Deletions of Two Adjacent Letters
1512A - Spy Detected
282A - Bit++
69A - Young Physicist
1651A - Playoff
734A - Anton and Danik
1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle
118A - String Task
236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters